package org.yun.octopus.base.core;

import org.yun.octopus.base.enums.RoleType;

import java.util.*;

import static org.yun.octopus.base.enums.ResType.FAIL;

/**
 * @author liyunfeng31s
 */
public class RollbackFactory{

    /**
     * stepNo -> rollback map
     */
    public static final Map<Integer, Rollback> ROLLBACK_MAP = new HashMap<>();

    /**
     * group -> allStepNos map
     */
    public static final Map<String, List<Integer>> GROUP_STEPS_MAP = new HashMap<>();


    /**
     * 初始化步骤和默认结果0的map step -> 0 map
     */
    public static final Map<Integer, Integer> STEP_RESULT_MAP = new HashMap<>();


    /**
     * 可信模式
     */
    public static final Set<String> RELIABLE_FLAGS = new HashSet<>();


    /**
     * 不可信模式
     */
    public static final Set<String> UNRELIABLE_FLAGS= new HashSet<>();

    static {
        RELIABLE_FLAGS.add("1");
        RELIABLE_FLAGS.add("2");
        UNRELIABLE_FLAGS.add("0");
        UNRELIABLE_FLAGS.add("1");
        UNRELIABLE_FLAGS.add("2");
    }

    public static Rollback getFallback(int stepNo){
        return ROLLBACK_MAP.get(stepNo);
    }

    public static List<Integer> getSteps(String group){
        return GROUP_STEPS_MAP.get(group);
    }


    public static void addFallback(Class<?> clz, String group, int stepNo, String fallback, RoleType role)
            throws InstantiationException, IllegalAccessException, NoSuchMethodException{

        List<Integer> steps = GROUP_STEPS_MAP.get(group);
        if (steps == null) { steps = new ArrayList<>(); }
        steps.add(stepNo);
        GROUP_STEPS_MAP.put(group, steps);
        STEP_RESULT_MAP.put(stepNo, FAIL.code());

        if(fallback == null || "".equals(fallback)){
            ROLLBACK_MAP.put(stepNo, null);
        }else{
            ROLLBACK_MAP.put(stepNo, new Rollback(clz.newInstance(), clz.getMethod(fallback, Long.class), role));
        }
    }


}
